package org.rapan.EJB;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.rapan.EmailBody;
import org.rapan.jpa.Consultant;
import org.rapan.jpa.Report;

@MessageDriven(name = "EDMProcessRequestQueueListener", activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "EmailQueue"),
		@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class EmailMDB implements MessageListener {

	@EJB
	ConsultantInt conInt;
	@EJB
	ReportInt repInt;

	@Override
	public void onMessage(Message m) {
		Set<EmailBody> mailSet = new HashSet<EmailBody>();

		try {
			String mName = m.getStringProperty("Name");
			if ("sReport".equalsIgnoreCase(mName)) {
				mailSet.addAll(generateSuccessfulRepMail(m));
			} else if ("fReport".equalsIgnoreCase(mName)) {
				mailSet.add(generateFailedRepMail(m));
			} else if ("consultEmail".equalsIgnoreCase(mName)) {
				mailSet.add(generateCreatedConsultantEmail(m));
			} else {
				return;
			}

			if (!mailSet.isEmpty()) {
				// connects to the mail server
				Properties props = new Properties();
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.socketFactory.port", "465");
				props.put("mail.smtp.socketFactory.class",
						"javax.net.ssl.SSLSocketFactory");
				props.put("mail.smtp.auth", "true");
				props.put("mail.smtp.port", "465");
				final String username = "atonchevpal@gmail.com";
				final String password = "*********";
				Session session = Session.getInstance(props,
						new javax.mail.Authenticator() {
							protected PasswordAuthentication getPasswordAuthentication() {
								return new PasswordAuthentication(username,
										password);
							}
						});

				// Session mailSession = (Session) ictx.lookup("java:/Mail");
				// gets the username and password needed to connect

				// creates a SMTP transport
				Transport transport = session.getTransport("smtp");
				try {
					// Makes a message element, filling it with the needed
					// information
					MimeMessage message = new MimeMessage(session);

					message.setFrom();
					transport.connect(username, password);
					for (EmailBody eBody : mailSet) {

						message.setRecipients(
								javax.mail.Message.RecipientType.TO,
								InternetAddress.parse(eBody.getEmail(), false));

						message.setSubject(eBody.getTitle());
						message.setText(eBody.getContent());
						message.saveChanges();
						// sends a mail for each element in the Set
						transport.sendMessage(message,
								message.getAllRecipients());
					}
				}

				finally {
					// closes the SMTP transport
					transport.close();
				}
			}

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private EmailBody generateCreatedConsultantEmail(Message m)
			throws JMSException {
		EmailBody emBody = new EmailBody();

		emBody.setEmail(m.getStringProperty("email"));
		emBody.setTitle("Registration at PASoft Consult");
		String content = "Greetings, "
				+ m.getStringProperty("fullName")
				+ ".\n"
				+ "An account has been created for you at PASoft Consult with the following login information: \n "
				+ "Username: " + emBody.getEmail() + "\n" + "Password: "
				+ m.getStringProperty("password") + "\n"
				+ "You can get to the application at : "
				+ m.getStringProperty("url") + "\n PASoft.";
		emBody.setContent(content);

		return emBody;
	}

	private EmailBody generateFailedRepMail(Message m) throws JMSException {
		EmailBody emBody = new EmailBody();
		Consultant c = conInt.view(m.getLongProperty("idConsultant"));
		emBody.setEmail(c.getEmail());
		emBody.setTitle("Invalid Report");
		StringBuilder content = new StringBuilder(
				c.getFullName()
						+ ", \n You failed to create a valid report due to the following reasons : \n");

		content.append(m.getStringProperty("errorList"));

		emBody.setContent(content.toString());
		return emBody;
	}

	private Set<EmailBody> generateSuccessfulRepMail(Message m)
			throws JMSException {
		EmailBody emBodyReciet = new EmailBody();
		EmailBody emBodyCon = new EmailBody();
		Report r = repInt.viewReport(m.getLongProperty("reportID"));
		emBodyReciet.setEmail(r.getCompany().getEmail());
		emBodyCon.setEmail(r.getConsultant().getEmail());
		emBodyReciet.setTitle("Job Receipt");
		emBodyCon.setTitle("Successful Report");
		emBodyCon.setContent("Report Created Successfully");
		emBodyReciet
				.setContent("Good day, "
						+ r.getCompany().getName()
						+ ", \n This is a work receipt for "
						+ repInt.getSum(r)
						+ " Hungarian Bananas, for the job done by "
						+ r.getConsultant().getFullName()
						+ ".\n "
						+ " The price is calculated by the coefficient of the rank of the consultant, multiplied by the total hours he worked for you, multiplied by the standard hourly wage. "
						+ "\n PASoft Consult.");
		Set<EmailBody> emSet = new HashSet<EmailBody>();
		emSet.add(emBodyCon);
		emSet.add(emBodyReciet);
		return emSet;
	}
}
